package com.heima.user.interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  Interceptor(springmvc技术)  <  过滤器（servlet技术）
 */
@Slf4j
public class ApUserTokenInterceptor implements HandlerInterceptor {
    /**
     * 前置通知  ThreadLocal 最大问题就是引起内存泄漏（OOM /CPU 100%）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //todo 1.从请求头中取出userId
        String userId = request.getHeader("userId");
        //todo 2.存放在一个共享的位置，任何地方都可以直接获取到
        if(null != userId && userId != ""){
            //代表userId有值  线程绑定  ThreadLocal 当前线程生效
            ApUser apUser = new ApUser();
            apUser.setId(Integer.parseInt(userId));
            ApUserThreadLocalUtil.setUser(apUser);
        }
        return true;
    }

    /**
     * 后置通知
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //清楚Threadlocal中的残留数据
        WmThreadLocalUtil.clear();
    }
}
